package com.ccrego.haiyi.common.web;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.support.annotation.Keep;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.ccrego.haiyi.account.AccountManager;
import com.ccrego.haiyi.account.login.H5ModifyPassWordActivity;
import com.ccrego.haiyi.account.login.LoginActivity;
import com.ccrego.haiyi.app.MainActivity;
import com.ccrego.haiyi.app.UploadAvatarFragment;
import com.ccrego.haiyi.common.http.TokenInfo;
import com.ccrego.haiyi.common.pay.AlipayHandler;
import com.ccrego.haiyi.common.pay.PayReceiver;
import com.ccrego.haiyi.common.pay.PayReceiverFail;
import com.ccrego.haiyi.common.pay.PayResultCallback;
import com.ccrego.haiyi.quickysee.QuickSeeActivity;
import com.ccrego.haiyi.wxapi.WXPayEntryActivity;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.cncn.youmengsharelib.ui.SharePlatformsFragment;
import com.pachong.android.framework.citypicker.ChooseCityDialogFragment;
import com.pachong.android.framework.citypicker.Province;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.NetUtil;
import com.pachong.android.frameworkbase.utils.SLog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import static com.ccrego.haiyi.account.AccountManager.getTokenInfo;


/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {
    private String locationProvider;
    private IWXAPI msgApi;
    private PayTask alipay;
    private PayReceiver payReceiver;
    private PayReceiverFail payReceiverFail;
    private CommonWebviewFragment mFragment;
    private UploadAvatarFragment avatarFragment;

    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;
        initPay();
        getToken();
        avatarFragment = new UploadAvatarFragment();
        fragment.getChildFragmentManager()
                .beginTransaction()
                .add(avatarFragment, "UploadAvatarFragment")
                .commit();

    }


    //初始化支付数据
    private void initPay() {
        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        //将该app注册到微信
        String wetharAppid = WXPayEntryActivity.WETHAR_APPID;
        msgApi.registerApp(wetharAppid);
        alipay = new PayTask(mFragment.getActivity());

        //支付成功的回调
        payReceiver = new PayReceiver(new PayResultCallback() {
            @Override
            public void onSuccess() {
                EasyToast.showToast(getContext(),"支付成功");
                mFragment.getWebview().loadUrl("javascript:afterPay(0)");
            }

            @Override
            public void onFail() {
                EasyToast.showToast(getContext(),"支付失败");
                mFragment.getWebview().loadUrl("javascript:afterPay(1)");
            }
        });
        getContext().registerReceiver(payReceiver, new IntentFilter(WXPayEntryActivity.WECHAR_PAY));

        //支付失败的回调
        payReceiverFail = new PayReceiverFail(new PayResultCallback() {
            @Override
            public void onSuccess() {
                EasyToast.showToast(getContext(),"支付失败");
                mFragment.getWebview().loadUrl("javascript:afterPay(1)");
            }

            @Override
            public void onFail() {
                EasyToast.showToast(getContext(),"支付失败");
                mFragment.getWebview().loadUrl("javascript:afterPay(1)");
            }
        });
        getContext().registerReceiver(payReceiverFail, new IntentFilter(WXPayEntryActivity.WECHAR_PAY_FAIL));
    }

    //


    //web调支付

    /**
     * 支付 paytype : 0表示支付宝，1表示微信支付
     *
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void pay(String orderNum) {
        Log.e("准备支付", "web use pay" + orderNum);
        try {
            JSONObject jsonObject = new JSONObject(orderNum);
            String payType = jsonObject.getString("type");
            //微信支付
            if (payType.equals("wxpay")) {
                String params = jsonObject.getString("params");
                onStartWechatPay(params);
            } else {
                String params = jsonObject.getString("params");
                JSONObject jsonObject1 = new JSONObject(params);
                String order_string = jsonObject1.getString("order_string");
                startAliPay(order_string);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除系统消息 或者活动消息  0系统。1活动
     *
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void cleanMessage(int type) {
    }

    /**
     * 返回经纬度
     *
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void  getLocation(String message) {
        Log.d("sss","getLocation  "+message);
       mFragment.getWebview().callJsFunction("onLocationSuccess",AccountManager.getCurrentAccount().getLongitude());
    }


    /**
     * 发起聊天
     */
    @Keep
    @JavascriptInterface
    @Override
    public void EaseChat(String phone, String customerName, String customerPortrait, String masterName, String masterPortrait) {
    }

    @Override
    public String getEaseChatList() {
        return null;
    }

    @Keep
    @JavascriptInterface
    @Override
    public void regionPicker(String info) {
        ChooseCityDialogFragment chooseCityDialog = new ChooseCityDialogFragment();
        chooseCityDialog.show(mFragment.getChildFragmentManager());
        chooseCityDialog.setOnCitySelectedListener(new ChooseCityDialogFragment.OnCitySelectedListener() {
            @Override
            public void onSelected(Province province, Province.City city, Province.Country country) {
                String s = "{" + "\"province\":" + "{" + "\"code\":" + "\"" + province.code + '\"' + "," + "\"label\":" + "\"" + province.label + '\"' + "}" +
                        ", \"city\":" + "{" + "\"code\":" + "\"" + city.code + '\"' + "," + "\"label\":" + "\"" + city.label + '\"' + "}" +
                        ", \"district\":" + "{" + "\"code\":" + "\"" + country.code + '\"' + "," + "\"label\":" + "\"" + country.label + '\"' + "}" +
                        '}';
//                Log.e("sssssss", s);
//                EventBus.getDefault().post(s);
                mFragment.callLoadUrl(s);
//                mFragment.getWebview().callJsFunction("onUploadSuccess", s);

            }
        });
    }


    private void startAliPay(final String params) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(params);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调用阿里支付
     */
    private AlipayHandler alipayHanlder = new AlipayHandler(new PayResultCallback() {

        @Override
        public void onSuccess() {
            SLog.e("onSuccess:"+"onSuccess");
            mFragment.getWebview().loadUrl("javascript:afterPay(0)");
        }

        @Override
        public void onFail() {
            mFragment.getWebview().loadUrl("javascript:afterPay(1)");
        }
    });//启动阿里支付回调的handle

    @Keep
    @JavascriptInterface
    @Override
    public String getToken() {
        String token = null;
        if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = getTokenInfo();
            token = tokenInfo.toString();
            Log.e("tokentoken",token);
//            token = GsonUtils.toJson(tokenInfo);
        }
        return token;
    }



    @Keep
    @JavascriptInterface
    @Override
    public void tocleanCache() {
        //清除缓存
        final File cacheDir = mFragment.getActivity().getCacheDir();
        final String cacheSize = FileUtils.size(cacheDir);
        //弹出Dialog
        showCacheDialog(cacheDir, cacheSize);
        FileUtils.delFilesFromPath(cacheDir);
    }

    //调用微信支付
    private void onStartWechatPay(String params) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(params);

            PayReq request = new PayReq();
            //微信分配的公众账号ID
            request.appId = jsonObject.getString("appid");
            //微信支付分配的商户号
            request.partnerId = jsonObject.getString("partnerid");
            //微信返回的支付交易会话ID
            request.prepayId = jsonObject.getString("prepayid");
            //暂填写固定值Sign=WXPay
            request.packageValue = jsonObject.getString("package");
            //随机字符串，不长于32位。推荐随机数生成算法
            request.nonceStr = jsonObject.getString("noncestr");
            //时间戳，请见接口规则-参数规定
            request.timeStamp = jsonObject.getString("timestamp");
            //签名，详见签名生成算法
            request.sign = jsonObject.getString("sign");
            msgApi.sendReq(request);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Keep
    @JavascriptInterface
    @Override
    public void login() {
        LoginActivity.start(getContext());
        Log.d("kyluzoi", "web use login");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void chooseUpload(String tag) {
        Log.e("tagtag", tag);
        avatarFragment.popupDialog();
//        {"type":"image","multi":false,"limit":1,"uploader":"http://server.haiyi.xmappservice.com/uploader/image","callback":"uploaderSuccess"}
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnCitySelectedListener(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void chooseShare(String shareJson) {
        Log.e("shareJson", shareJson);
        try {
            JSONObject jsonObject = new JSONObject(shareJson);
            String title = jsonObject.getString("title");
            String desc = jsonObject.getString("desc");
            String imgUrl = jsonObject.getString("imgUrl");
            String link = jsonObject.getString("link");
            SharePlatformsFragment fragment = SharePlatformsFragment.newInstance(title, desc, imgUrl, link);
            fragment.setShareListener(new ShareListener() {
                @Override
                public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "取消分享", Toast.LENGTH_SHORT).show();
                }
            });
            fragment.show(mFragment.getFragmentManager(), "");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    //上下文
    private Context getContext() {
        return mFragment.getContext();
    }

    //退出登录
    @Keep
    @JavascriptInterface
    @Override
    public void logout() {
        //弹出Dialog
        showDialog();
//        getMessageDao().deleteAll();
    }




    @Keep
    @JavascriptInterface
    @Override
    public void enterFastLook() {
        Log.d("enterFastLook", "enterFastLook");
        QuickSeeActivity.start(getContext());
    }

    private void showDialog() {
        final AlertDialogFragment dialogOutFragment = new AlertDialogFragment();
        dialogOutFragment.setMessage("是否确定退出？").setNegativeButton("取消",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogOutFragment.dismiss();
                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AccountManager.getTokenInfo().clear();
                        dialogOutFragment.dismiss();
                        //避免返回到退出的界面
                        LoginActivity.start(getContext());
                        mFragment.getActivity().finish();
                    }
                })
                .show(mFragment.getFragmentManager());

    }


    //忘记密码
    @Keep
    @JavascriptInterface
    @Override
    public void forgetWord() {
        //弹出Dialog
        H5ModifyPassWordActivity.start(mFragment.getActivity());
    }

    private void showCacheDialog(final File cacheDir, final String cacheSize) {
        if ("0B".equals(cacheSize)) {
            final AlertDialogFragment nullCacheDialogFrag = new AlertDialogFragment();
            nullCacheDialogFrag.setMessage("无缓存")
                    .setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            nullCacheDialogFrag.dismiss();
                        }
                    }).show(mFragment.getFragmentManager());
        } else {
            final AlertDialogFragment cleanDialogFrag = new AlertDialogFragment();
            cleanDialogFrag.setMessage("确认清除" + cacheSize + "缓存?")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cleanDialogFrag.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            FileUtils.delFilesFromPath(cacheDir);
                            cleanDialogFrag.dismiss();
                            Toast.makeText(getContext(), "已清除" + cacheSize + "缓存!", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .show(mFragment.getFragmentManager());
        }
    }
}
